# coding:utf-

import re
import os
import datetime

# 将srt文件内容转化成vtt内容
import requests
from io import StringIO
from urllib import request

from bson import ObjectId

from dao.VideoDao import addSentiment, readCaption
from sentiment.utils.LanguageUtil import check_contain_chinese
from sentiment.snownlp_textblob.beiyesSentiment import BeiyesSentiment


def srt2vtt(content):
    #     content = open(file_name, "r", encoding="utf-8").read()
    # 添加WEBVTT行

    content = "WEBVTT\n\n" + content
    # 替换“,”为“.”
    content = re.sub("(\d{2}:\d{2}:\d{2}),(\d{3})", lambda m: m.group(1) + '.' + m.group(2), content)
    #     output_file = os.path.splitext(file_name)[0] + '.vtt'
    #     open(output_file, "w", encoding="utf-8").write(content)
    return content


# 解析srt文件，返回数组
def srt2arr(str):
    str = str.replace('\n\n', '\n')
    # 需要在序号前面补上换行
    str = re.sub(r'\n(\d{1,3})\n', r'\n\n\1\n', str)
    # 修正其他字符错误
    str = str.replace('- - ', '--')

    pattern = re.compile(r'^\d+$', re.M)
    arr = pattern.split(str)
    # [[time,str], [time, str]]
    result = []

    base_time = datetime.datetime.strptime('00:00:00', "%H:%M:%S")
    base_time2 = datetime.datetime.strptime('00:00:15', "%H:%M:%S")

    for a in arr:
        if a == '':
            continue
        a = a.strip()
        cell = a.split('\n')
        times = cell[0].split('-->')
        s_start = times[0].strip()
        start = (datetime.datetime.strptime(s_start.split(',')[0], "%H:%M:%S") - base_time).total_seconds()
        s_end = times[1].strip()
        end = (datetime.datetime.strptime(s_end.split(',')[0], "%H:%M:%S") - base_time).total_seconds()
        result.append([(start, end), cell[1:]])
    return result


# 解析srt文件，返回数组
def vtt2arr(str):
    str = str.replace('\n\n', '\n')
    str = str.replace('\r', '')
    # 需要在序号前面补上换行
    str = re.sub(r'\n(\d{1,3})\n', r'\n\n\1\n', str)
    # 修正其他字符错误
    str = str.replace('- - ', '--')

    pattern = re.compile(r'^\d+$', re.M)
    arr = pattern.split(str)
    arr = arr[1:]
    # [[time,str], [time, str]]
    result = []

    base_time = datetime.datetime.strptime('00:00:00', "%H:%M:%S")
    # base_time2 = datetime.datetime.strptime('00:00:15', "%H:%M:%S")

    for a in arr:
        if a == '':
            continue
        a = a.strip()
        cell = a.split('\n')
        times = cell[0].split('-->')
        s_start = times[0].strip()
        start = (datetime.datetime.strptime(s_start.split('.')[0], "%H:%M:%S") - base_time).total_seconds()
        s_end = times[1].strip()
        end = (datetime.datetime.strptime(s_end.split('.')[0], "%H:%M:%S") - base_time).total_seconds()
        result.append([(start, end), cell[1:]])
    return result


# [[(0,7),'xxxx',1],...]  情感分析
# 关键词提取
# ([[(0,7),['xxx','xxx'],'zh|en',0.8],...], [keywords])
def renderCaption(videoId):
    content, ext = readCaption(videoId)
    if ext == 'srt':
        from app import db
        tbVideo = db["video"]
        content = srt2vtt(content)
        query = {"_id": ObjectId(videoId)}
        newvalues = {"$set": {"captionExt": 'vtt', 'captionText': content}}
        tbVideo.update_one(query, newvalues)
    result = vtt2arr(content)
    # 字幕文本连接成整个文本
    text = ''
    posGrade = 0
    negGrade = 0
    for item in result:
        text = text + ''.join(item[1])
        if check_contain_chinese(''.join(item[1])):
            item.append('zh')
            sentiment = BeiyesSentiment.chinese_analyse(''.join(item[1]))
            item.append(sentiment)
            posGrade += sentiment
            negGrade += (1-sentiment)
        else:
            item.append('en')
            sentiment = BeiyesSentiment.english_analyse(''.join(item[1]))
            item.append(sentiment)
            # if sentiment > 0:
            #     posGrade = posGrade + 1
            # else:
            #     negGrade = negGrade + 1
            posGrade += sentiment
            negGrade += (1 - sentiment)
    keywords = BeiyesSentiment.chinese_keyword(text, 10)
    # 保存到数据库
    addSentiment(videoId, result, keywords, posGrade, negGrade);
    return {
        'code':0
    }



if __name__ == '__main__':
    vttPath = 'zh.vtt'
    arr = vtt2arr(open(vttPath, 'r', encoding='utf-8').readlines())
    print(arr)
